package base

import (
	"encoding/json"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/base/user"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

type LoginController struct {
	controller.BaseController
	userService  user.UserSerivceIface
	loginService user.LoginServiceIface
}

func NewLoginController(
	userService user.UserSerivceIface,
	loginService user.LoginServiceIface,
) *LoginController {
	return &LoginController{
		userService:  userService,
		loginService: loginService,
	}
}

const CHECK_CLEAN_CODE = "check_clean_code"

func (l *LoginController) RegisterRouter(g *gin.RouterGroup) {
	g.POST("/login-by-account-password", l.LoginByAccountPassword)
	//主应用的sso登录
	g.GET("/sso", l.Sso)
	g.GET("/logout", l.Logout)
}

// 联合用户登录
func (l *LoginController) LoginByAccountPassword(ctx *gin.Context) {
	var params = make(map[string]interface{})
	err := json.NewDecoder(ctx.Request.Body).Decode(&params)
	if err != nil {
		l.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	tenantCode, _ := params["tenant_code"].(string)
	account, _ := params["account"].(string)
	password, _ := params["password"].(string)

	if password == "" {
		l.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "password为空")
		return
	}

	userLoginInfo, err := l.userService.UserLogin(ctx, tenantCode, account, password)
	if err != nil {
		//grpcErr := rpc_client.GetGrpcError(err)
		//errCode := errcode.COMMON_USER_UNBIND
		//errMessage := err.Error()
		//if grpcErr != nil && grpcErr.GetCode() == 20020002 {
		//	errCode = errcode.COMMON_USER_FORBIDDEN
		//	errMessage = grpcErr.GetMessage()
		//}

		l.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	//if err != nil {
	//	l.Fail(ctx, errcode.COMMON_USER_UNBIND, err.Error())
	//	return
	//}

	l.Success(ctx, userLoginInfo)
}

// 退出登录
func (l *LoginController) Logout(ctx *gin.Context) {
	token := ctx.Request.Header.Get("token")
	if token == "" {
		l.Fail(ctx, errcode.COMMON_USER_IDENTITY_ERROR, "缺少token")
	}
	//
	//globalUserId := utils.GetGlobalUserId(ctx)
	//if globalUserId == "" {
	//	l.Fail(ctx, errcode.COMMON_TOKEN_ERROR, ykerrcode.GetErrMsg(errcode.COMMON_TOKEN_ERROR))
	//	return
	//}
	err := l.userService.UserLogout(ctx, token)
	if err != nil {
		l.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	l.Success(ctx, nil)
}

// 单点登录sso(单点登录主应用)
func (l *LoginController) Sso(ctx *gin.Context) {
	accessToken := ctx.Query("access_token")
	pageUri := ctx.Query("page_uri")

	//// 模拟生成access_token
	//accessToken, err := jwt.DefaultJWT.GenerateMainAppToken("mysoft", "admin")
	//if err != nil {
	//	l.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
	//	return
	//}
	//res, err := jwt.DefaultJWT.ParseMainAppToken(accessToken, jwt.DEFAULT_SINGKEY)
	//if err != nil {
	//	l.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
	//	return
	//}
	//fmt.Println(res)
	mainAppToken, err := l.userService.SsoLogin(ctx, accessToken)
	if err != nil {
		l.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	if accessToken == "" {
		// todo 做成错误页面
		l.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "access_token不能为空")
		return
	}
	if pageUri == "" {
		// todo 做成错误页面
		l.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "page_uri不能为空")
		return
	}
	// gfyxFrontDomain https://gfyx.b2btst.com
	var gfyxFrontDomain = stark.Configer.(stark.ApolloConfigerIface).GetStringValue("gfyx_front_domain", "")
	parmaLinkVar := "?"
	if strings.Index(pageUri, "?") != -1 {
		parmaLinkVar = "&"
	}
	ctx.Redirect(http.StatusFound, gfyxFrontDomain+pageUri+parmaLinkVar+"token="+mainAppToken) //302 临时重定向
}
